﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using HostTool.Core;
using HostTool.GUI;
using System.IO.Ports;
using System.IO;
using System.Threading;

namespace HostTool
{
    public partial class FormMain : Form
    {


        FormMonitor formMonitor;


        public FormMain()
        {
            InitializeComponent();
          
        }


        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            InitSerialPort(); //初始化串口
            InitBoardList();


            string fileName = Path.Combine(Application.StartupPath,"Version.txt");
            if (File.Exists(fileName))
            {
                btInnerVersions.Visible = true;
            }

        }

        void InitSerialPort()
        {
            toolStripComboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports)
            {

                toolStripComboBox1.Items.Add(port);
            }
            if (toolStripComboBox1.Items.Count > 0)
            {
                toolStripComboBox1.SelectedIndex = 0;
            }
        }

        void InitBoardList()
        {
            HostMachine machine = MachineManager.GetMachine();

            boardListBar.Groups.Clear();

            foreach (IBoard board in machine.Boards)
            {
               Infragistics.Win.UltraWinListBar.Group group= boardListBar.Groups.Add();
               group.Text = board.Name;

               foreach (ICPU cpu in board.CPUS)
               {
                   Infragistics.Win.UltraWinListBar.Item item = group.Items.Add();
                   item.Text = cpu.Name;
                   item.Tag = cpu;
                   item.LargeImageIndex = 0;
               }
            }
        }

        private void boardListBar_ItemSelected(object sender, Infragistics.Win.UltraWinListBar.ItemEventArgs e)
        {
            ICPU cpu = e.Item.Tag as ICPU;
            if (cpu == null) return;
            cpu.ClearData();
            panelForms.Controls.Clear();
            if (cpu is LinkBoardCPU)
            {
                FormCPU form = new FormCPU(cpu as LinkBoardCPU);
                form.TopLevel = false;
                form.FormBorderStyle = FormBorderStyle.None;
                form.Dock = DockStyle.Fill;
                panelForms.Controls.Add(form);

                form.Show();
            }
            else if (cpu is CPUSample) //记录板采样CPU
            {
                FormCPU form = new FormCPU(cpu as CPUSample);
                form.TopLevel = false;
                form.FormBorderStyle = FormBorderStyle.None;
                form.Dock = DockStyle.Fill;
                panelForms.Controls.Add(form);

                form.Show();
            }
            else if (cpu is CPURecord)
            {
                FormCPU form = new FormCPU(cpu as CPURecord);
                form.TopLevel = false;
                form.FormBorderStyle = FormBorderStyle.None;
                form.Dock = DockStyle.Fill;
                panelForms.Controls.Add(form);

                form.Show();
            }
            else if (cpu is TestBoxCPU)
            {
                FormCPU form = new FormCPU(cpu as TestBoxCPU);
                form.TopLevel = false;
                form.FormBorderStyle = FormBorderStyle.None;
                form.Dock = DockStyle.Fill;
                panelForms.Controls.Add(form);

                form.Show();
            }
            else if (cpu is HostDecodeCPU) //主机板解码CPU
            {
                FormHostDecodeCPU form = new FormHostDecodeCPU(cpu as HostDecodeCPU);
                form.TopLevel = false;
                form.FormBorderStyle = FormBorderStyle.None;
                form.Dock = DockStyle.Fill;
                panelForms.Controls.Add(form);

                form.Show();
            }
            else if (cpu is HostControlCPU) //主机板控制CPU
            {
                FormHostControlCPU form = new FormHostControlCPU(cpu as HostControlCPU);
                form.TopLevel = false;
                form.FormBorderStyle = FormBorderStyle.None;
                form.Dock = DockStyle.Fill;
                panelForms.Controls.Add(form);

                form.Show();
            }
            
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            HostMachine machine = MachineManager.GetMachine();
            if (machine.IsRunning)
            {
                machine.Stop();
                toolStripComboBox1.Enabled = true;
                buttonStart.Image = Properties.Resources.Start;
                buttonStart.Text = "开启";
            }
            else
            {
                machine.PortName = toolStripComboBox1.Text;
                machine.Start();
                toolStripComboBox1.Enabled = false;
                buttonStart.Image = Properties.Resources.Stop;
                buttonStart.Text = "终止";
            }
      
        }


        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            HostMachine machine = MachineManager.GetMachine();
            machine.FrameManager.RequesStop(); 
            
        }

        private void buttonMonitor_Click(object sender, EventArgs e)
        {
            if (formMonitor == null || formMonitor.IsDisposed)
            {
                formMonitor = new FormMonitor();
                formMonitor.Owner = this;
                formMonitor.Show();
            }
            else
            {
                formMonitor.BringToFront();

            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Filter = "固件程序(*.bin)|*.bin|参数文件(*.txt)|*.txt";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    byte[] data = File.ReadAllBytes(ofd.FileName);
                    byte[] dataC = data;

                    if (ofd.FilterIndex == 2) //参数文件
                    {
                        HostParamFirmType typeConvert = new HostParamFirmType("",1);
                        dataC = typeConvert.Convert(data);
                    }

                    StringBuilder sb = new StringBuilder();

                    sb.AppendLine("/*********************************************************************************");
                    sb.AppendLine("Do Not Change !!");
                    sb.AppendLine("*********************************************************************************/");



                    sb.AppendLine("const char firmware["+ dataC.Length.ToString()+"]={");

                    for (int i = 0; i < dataC.Length; i++)
                    {
                        sb.Append("0x"+dataC[i].ToString("X2")+",");
                        if ((i + 1) % 16 == 0)
                        {
                            sb.AppendLine();
                        }
                    }
                    sb.AppendLine();
                    sb.AppendLine("};");

                    string cFileName =Path.Combine(Path.GetDirectoryName(ofd.FileName), Path.GetFileNameWithoutExtension(ofd.FileName)+".c");


                    File.WriteAllText(cFileName, sb.ToString());


                    MessageBox.Show("C文件生成OK!!");

                }
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("程序日期:2013/10/10                       \r\n程序版本:V1.0.0.0", "程序版本", MessageBoxButtons.OK,MessageBoxIcon.Information);
        }

        private void btInnerVersions_Click(object sender, EventArgs e)
        {
            FormVersion formVersion = new FormVersion();
            formVersion.Owner = this;
            formVersion.StartPosition = FormStartPosition.CenterParent;
            formVersion.Show();
        }

        private void toolStripButtonParam_Click(object sender, EventArgs e)
        {
            FormCPUParam frmParam = new FormCPUParam();

            //frmParam.Owner = this;
            frmParam.Show();
        }


    }
}
